#include"myregex.h"
#include <assert.h>
char* suffix;
bool is_exist(const char* filename)
{
    return access(filename,F_OK)==0;
 }
bool is_empty(const char* line)
{
   if(line==NULL) return true;
   if(!line) return true;
   for(register int i=0;i<(int)(strlen(line)/sizeof(char));i++)
        {
                if(!isspace((int)line[i]))
                      return false;
                }       
		      return true;	
}
mylink<string,mat>* myregex(const char* dir,const char* str_name, char* file_type)
{  
   // printf("myregex:%s\n",dir);
    suffix=file_type;  
    mylink<string,mat>* mat_link=new mylink<string,mat>();
    snode<string,mat> *file_snode; 
    node<mat> *mat_node;
    //match string;
    regex_t reg;
    mat rez_match;
    int reg_z;
    char *dirpath=NULL;
    string strline,filename;
    const int nmatch=10;
    const int aflag=0;
    regmatch_t rezult_reg[nmatch];
    long lineno=0;
    r_list<string> *xfilename;
    string open_file_name,fileline;
    xfilename=new r_list<string>;
   
	reg_z=regcomp(&reg,str_name,0);
    if(reg_z!=0)
            {
                     throw new error_reg(reg,reg_z);
              }   
   dirpath=const_cast<char*>(dir);
   assert(dirpath!=NULL);
   char* p;
   if(*(p=dirpath+(strlen(dirpath)-1))=='/')
        *p=0;
   myfind(dirpath,xfilename); 
   xfilename->athead();
 while(xfilename->Currnode()!=NULL)
    {
       ifstream readfile;
       open_file_name=xfilename->Data();
       file_snode=new snode<string,mat>(open_file_name); 
        mat_link->insert(file_snode);
      readfile.open(open_file_name.c_str(),ios::in);
      if(!readfile)
           {
             throw new error_name("read file fail");
          }
      while(getline(readfile,fileline,'\n'))
         {
             lineno++;
    reg_z=regexec(&reg,fileline.c_str(),nmatch,rezult_reg,aflag);
    if(reg_z==REG_NOMATCH) continue;
    if(reg_z!=0)
            {
                     throw new error_reg(reg,reg_z);
              }
    for(register int i=0;i<nmatch && rezult_reg[i].rm_so!=-1;++i)
          {
            
              if(!i)
                  {
               rez_match.line_no=lineno;
               rez_match.linecontext=fileline;
               mat_node=new node<mat>(rez_match);
               mat_link->insert(open_file_name,mat_node);   
                    }
             }
     }
     readfile.close();      
          lineno=0;
          xfilename->Next();    
        }
 //   mat_link.mat_print(); 
    regfree(&reg);
    delete xfilename;
    return mat_link;
}

void  myregex(QWidget* parent,const char* dir,const char* str_name,const char* file_type,QListWidget* list)
{
	char* filetype = const_cast<char*>(file_type);
	mylink<string,mat>* shead;
	try{
		 shead = myregex(dir,str_name,filetype);
	}
	catch(myerror* e)
	{
		QMessageBox::warning(parent, QObject::tr("Prompt"),QString(e->what()),QMessageBox::Yes,QMessageBox::NoButton);
		return ;
	}
	shead->display_QEdit_Text(list);
	shead->destroy();
}
